package com.lanchetech.service.impl;


import com.alibaba.excel.util.CollectionUtils;
import com.lanchetech.common.enums.*;
import com.lanchetech.dao.*;
import com.lanchetech.entity.*;
import com.lanchetech.service.CommissionService;
import com.lanchetech.service.DaoService;
import com.lanchetech.service.GroupService;
import com.lanchetech.service.LevelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.lanchetech.common.constants.JypConstant.HIPO_USER_ID;


@Service
public class LevelServiceImpl implements LevelService {

    @Autowired
    UserCommissionMapper userCommissionMapper;

    @Autowired
    CommissionService commissionService;

    @Autowired
    IdentityMapper identityMapper;

    @Autowired
    UserRelationshipMapper userRelationshipMapper;

    @Autowired
    BonusCountMapper bonusCountMapper;

    @Autowired
    DaoService daoService;

    @Autowired
    UserMapper userMapper;

    @Autowired
    RewardQueueMapper rewardQueueMapper;

    @Autowired
    GroupService groupService;

    @Autowired
    AdFlowMapper adFlowMapper;

    @Autowired
    CardFlowMapper cardFlowMapper;

    @Autowired
    BossIdentityMapper bossIdentityMapper;

    private Map<String, String> hipoConfig;

    @Override
    public void addOneRecommend(User user, Byte isBuyer) {
        Identity result = identityMapper.findOneByUserId(user.getId());
        if (result == null) {
            Identity subordinateIdentity = Identity.builder()
                    .userId(user.getId())
                    .singleShop(0L)
                    .level(0)
                    .memberLevel(0)
                    .partnerLevel(0)
                    .shareholderLevel(0)
                    .memberL4Grade(0)
                    .partnerL4Grade(0)
                    .shareholderL4Grade(0)
                    .memberL1Number(0L)
                    .memberL2Number(0L)
                    .memberL3Number(0L)
                    .partnerL1Number(0L)
                    .partnerL2Number(0L)
                    .partnerL3Number(0L)
                    .shareholderL1Number(0L)
                    .shareholderL2Number(0L)
                    .shareholderL3Number(0L)
                    .type(IdentityTypeEnum.MEMBER.getType())
                    .isBuyer(isBuyer)
                    .createdAt(new Date())
                    .updateAt(new Date())
                    .director(DirectorEnum.NORMAL.getType())
                    .anchorLevel(AnchorLevelEnum.NOT_ANCHOR.getLevel())
                    .partnerAccount(0)
                    .areaAccount(0)
                    .teacherLevel(TeacherLevelEnum.DEFAULT.getLevel())
                    .recommendLevel(RecommendLevelEnum.V1.getLevel())
                    .memberState(MemberStateEnum.LOW.getType())
                    .memberAccount(0)
                    .staticDividend(BigDecimal.ZERO)
                    .shareholderState(ShareholderStateEnum.DEFAULT.getType())
                    .sellCount(0L)
                    .welfare(BigDecimal.ZERO)
                    .commissionCount(0L)
                    .inviteCount(0)
                    .inviteRewardLevel(0)
                    .newZoneBuy(ToggleEnum.OFF.getStatus())
                    .build();
            identityMapper.insert(subordinateIdentity);
        }
    }

    @Override
    public void addLowMember(User user) {
        Identity result = identityMapper.findOneByUserId(user.getId());
        if (result == null) {
            Boolean hasNewZone = checkNewZone(user);
            Identity subordinateIdentity = Identity.builder()
                    .userId(user.getId())
                    .singleShop(0L)
                    .level(UserLevelEnum.MEMBER_L1.getLevel())
                    .memberLevel(UserLevelEnum.MEMBER_L1.getLevel())
                    .partnerLevel(0)
                    .shareholderLevel(0)
                    .memberL4Grade(0)
                    .partnerL4Grade(0)
                    .shareholderL4Grade(0)
                    .memberL1Number(0L)
                    .memberL2Number(0L)
                    .memberL3Number(0L)
                    .partnerL1Number(0L)
                    .partnerL2Number(0L)
                    .partnerL3Number(0L)
                    .shareholderL1Number(0L)
                    .shareholderL2Number(0L)
                    .shareholderL3Number(0L)
                    .type(IdentityTypeEnum.MEMBER.getType())
                    .isBuyer(IsBuyerEnum.BUYER.getType())
                    .createdAt(new Date())
                    .updateAt(new Date())
                    .director(DirectorEnum.NORMAL.getType())
                    .anchorLevel(AnchorLevelEnum.NOT_ANCHOR.getLevel())
                    .partnerAccount(0)
                    .areaAccount(0)
                    .teacherLevel(TeacherLevelEnum.DEFAULT.getLevel())
                    .recommendLevel(RecommendLevelEnum.V1.getLevel())
                    .memberExpireTime(new Date())
                    .memberState(MemberStateEnum.LOW.getType())
                    .memberAccount(0)
                    .staticDividend(BigDecimal.ZERO)
                    .shareholderState(ShareholderStateEnum.DEFAULT.getType())
                    .sellCount(0L)
                    .welfare(BigDecimal.ZERO)
                    .commissionCount(0L)
                    .inviteCount(0)
                    .inviteRewardLevel(0)
                    .newZoneBuy(hasNewZone ? ToggleEnum.ON.getStatus():ToggleEnum.OFF.getStatus())
                    .build();
            identityMapper.insert(subordinateIdentity);
            updateUserLevel(user.getId(), UserLevelEnum.MEMBER_L1.getLevel());

            // 获取用户上级
            UserRelationship userRelationship = userRelationshipMapper.findOneBySubordinateId(user.getId());

            Long issueSuperiorId = null;
            if (userRelationship != null) {

                Long superiorId = userRelationship.getSuperiorId();
                Identity superiorIdentity = identityMapper.findOneByUserId(superiorId);

                // 购买和赠送都算人头
                if (superiorIdentity != null) {
                    // 发放会员一级分销佣金（任何等级）
                    issueSuperiorId = superiorId;
                }
            }

            // 加入团队
            groupService.createUserGroup(issueSuperiorId, user);
        }
    }

    private Boolean checkNewZone(User user) {
        Boolean hasNewZone = false;
        List<Long> ids = userMapper.findIdByUsernameLike(user.getUsername());
        if (!CollectionUtils.isEmpty(ids)) {
            Byte maxNewZone = identityMapper.findMaxNewZoneByUserIds(ids);
            if (maxNewZone != null && maxNewZone > 0) {
                hasNewZone = true;
            }
        }
        return hasNewZone;
    }


    /**
     * 分红生效时间不变
     *
     * @return
     */
    private Date getEffectTime() {
        Calendar effectCalendar = Calendar.getInstance();
        effectCalendar.add(Calendar.DATE, 28);
        effectCalendar.set(Calendar.MILLISECOND, 0);
        effectCalendar.set(Calendar.SECOND, 0);
        effectCalendar.set(Calendar.MINUTE, 0);
        effectCalendar.set(Calendar.HOUR_OF_DAY, 0);
        return effectCalendar.getTime();
    }

    private Date getEffectTimeByDay(Integer day) {
        Calendar effectCalendar = Calendar.getInstance();
        effectCalendar.add(Calendar.DATE, day);
        effectCalendar.set(Calendar.MILLISECOND, 0);
        effectCalendar.set(Calendar.SECOND, 0);
        effectCalendar.set(Calendar.MINUTE, 0);
        effectCalendar.set(Calendar.HOUR_OF_DAY, 0);
        return effectCalendar.getTime();
    }

    @Override
    public void addOneMember(User user, Byte isBuyer, Byte memberState) {

        Identity result = identityMapper.findOneByUserId(user.getId());

        this.hipoConfig = daoService.getHipoConfigMap();

        // 会员允许重复购买，重复购买就等于反复续费，每次购买+1年
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.YEAR, 1);

        // 是否首次创建会员
        boolean isCreate = true;


        if (result != null) {
            if (result.getLevel() < UserLevelEnum.MEMBER_L1.getLevel()) {
                result.setLevel(UserLevelEnum.MEMBER_L1.getLevel());
                result.setType(IdentityTypeEnum.MEMBER.getType());
                result.setMemberLevel(UserLevelEnum.MEMBER_L1.getLevel());
                result.setIsBuyer(isBuyer);
                result.setMemberExpireTime(calendar.getTime());
                result.setMemberState(memberState);
                identityMapper.updateByPrimaryKeySelective(result);

                updateUserLevel(user.getId(), UserLevelEnum.MEMBER_L1.getLevel());
            } else {
                // 如果已经是合伙人，股东或以上，则设置或续期
                if (result.getMemberLevel().equals(0)) {
                    result.setMemberLevel(UserLevelEnum.MEMBER_L1.getLevel());
                } else {
                    if (MemberStateEnum.HIGH.getType().equals(result.getMemberState()) || MemberStateEnum.SUPER.getType().equals(result.getMemberState())) {
                        isCreate = false;
                    } else {
                        result.setMemberState(memberState);
                    }
                }
                if (result.getMemberExpireTime() != null) {
                    Calendar calendar3 = Calendar.getInstance();
                    calendar3.add(Calendar.YEAR, 10); // 最大为将近4年
                    if (result.getMemberExpireTime().before(calendar3.getTime())) {
                        if (result.getMemberExpireTime().after(new Date())) {
                            calendar.setTime(result.getMemberExpireTime());
                            calendar.add(Calendar.YEAR, 1);
                        }
                        result.setMemberExpireTime(calendar.getTime());
                    }
                } else {
                    result.setMemberExpireTime(calendar.getTime());
                }
                if (result.getShareholderLevel() < UserLevelEnum.SHAREHOLDER_L1.getLevel() && IsBuyerEnum.GIFT.getType().equals(result.getIsBuyer())) {
                    result.setIsBuyer(isBuyer);
                }
                identityMapper.updateByPrimaryKeySelective(result);
            }
        } else {
            Identity subordinateIdentity = Identity.builder()
                    .userId(user.getId())
                    .singleShop(0L)
                    .level(UserLevelEnum.MEMBER_L1.getLevel())
                    .memberLevel(UserLevelEnum.MEMBER_L1.getLevel())
                    .partnerLevel(0)
                    .shareholderLevel(0)
                    .memberL4Grade(0)
                    .partnerL4Grade(0)
                    .shareholderL4Grade(0)
                    .memberL1Number(0L)
                    .memberL2Number(0L)
                    .memberL3Number(0L)
                    .partnerL1Number(0L)
                    .partnerL2Number(0L)
                    .partnerL3Number(0L)
                    .shareholderL1Number(0L)
                    .shareholderL2Number(0L)
                    .shareholderL3Number(0L)
                    .type(IdentityTypeEnum.MEMBER.getType())
                    .isBuyer(isBuyer)
                    .createdAt(new Date())
                    .updateAt(new Date())
                    .director(DirectorEnum.NORMAL.getType())
                    .anchorLevel(AnchorLevelEnum.NOT_ANCHOR.getLevel())
                    .partnerAccount(0)
                    .areaAccount(0)
                    .teacherLevel(TeacherLevelEnum.DEFAULT.getLevel())
                    .recommendLevel(RecommendLevelEnum.V1.getLevel())
                    .memberExpireTime(calendar.getTime())
                    .memberState(memberState)
                    .memberAccount(0)
                    .staticDividend(BigDecimal.ZERO)
                    .dividendEffectTime(null)
                    .shareholderState(ShareholderStateEnum.DEFAULT.getType())
                    .sellCount(0L)
                    .welfare(BigDecimal.ZERO)
                    .commissionCount(0L)
                    .inviteCount(0)
                    .inviteRewardLevel(0)
                    .newZoneBuy(ToggleEnum.OFF.getStatus())
                    .build();
            identityMapper.insert(subordinateIdentity);
            updateUserLevel(user.getId(), UserLevelEnum.MEMBER_L1.getLevel());
        }


        // 获取用户上级
        UserRelationship userRelationship = userRelationshipMapper.findOneBySubordinateId(user.getId());

        Long issueSuperiorId = null;
        if (userRelationship != null) {

            // 只要没绑定，就将上下级状态设置为已绑定
            if (!RelationshipStatusEnum.BIND.getStatus().equals(userRelationship.getStatus())) {
                userRelationship.setStatus(RelationshipStatusEnum.BIND.getStatus());
                userRelationship.setUpdatedAt(new Date());
                userRelationshipMapper.updateByPrimaryKeySelective(userRelationship);
            }

            Long superiorId = userRelationship.getSuperiorId();
            Identity superiorIdentity = identityMapper.findOneByUserId(superiorId);

            // 购买和赠送都算人头
            if (superiorIdentity != null && isCreate) {
                // 只要上级是会员，则记录邀请数量;必须是高级会员
                if (superiorIdentity.getMemberLevel() >= UserLevelEnum.MEMBER_L1.getLevel()
                        && (MemberStateEnum.HIGH.getType().equals(superiorIdentity.getMemberState()) || MemberStateEnum.SUPER.getType().equals(superiorIdentity.getMemberState()))) {
                    superiorIdentity.setMemberL1Number(superiorIdentity.getMemberL1Number() + 1);

                    isPromotion(superiorIdentity, IdentityTypeEnum.MEMBER);
                }
                // 发放会员一级分销佣金（任何等级）
                issueSuperiorId = superiorId;
            }
        }

        // 加入团队
        groupService.createUserGroup(issueSuperiorId, user);

        // 仅购买者发放嗨币
//        if (IsBuyerEnum.BUYER.getType().equals(isBuyer)) {
//            // 晋级会员计数
//            BonusCount bonusCount = bonusCountMapper.findOneByRewardType(RewardTypeEnum.MEMBER_L4.getType());
//            bonusCount.setCount(bonusCount.getCount() + 1L);
//            if (bonusCount.getCount() >= Integer.valueOf(this.hipoConfig.get(HipoConfigEnum.MEMBER_L4_PERIOD.getConfig()))) {
//                bonusCount.setCount(0L);
//                // 发放晋级总监奖励
//                RewardQueue rewardQueue = rewardQueueMapper.findOneByRewardTypeAndQueueStatusForReward(RewardTypeEnum.MEMBER_L4.getType(), ToggleEnum.OFF.getStatus());
//                if (rewardQueue != null) {
//                    // 要自行到公司领取钱，当前只记录为已经排单
//                    rewardQueue.setQueueStatus(ToggleEnum.ON.getStatus());
//                    rewardQueue.setUpdateAt(new Date());
//                    rewardQueueMapper.updateByPrimaryKeySelective(rewardQueue);
//
//                    // 直接发放佣金
//                    // 设置冻结时间
//                    Calendar cal = Calendar.getInstance();
//                    cal.add(Calendar.DATE, 15);
//                    userCommissionMapper.insert(UserCommission.builder()
//                            .superiorId(rewardQueue.getUserId())
//                            .subordinateId(HIPO_USER_ID)
//                            .orderSkuId(null)
//                            .commission(rewardQueue.getAmount())
//                            .type(UserCommissionTypeEnum.MEMBER_L4_BONUS.getType())
//                            .freezeTime(cal.getTime())
//                            .status(UserCommissionStatusEnum.FREEZE.getStatus())
//                            .relateId(rewardQueue.getId())
//                            .remark(UserCommissionTypeEnum.MEMBER_L4_BONUS.getRemark())
//                            .createdAt(new Date())
//                            .updatedAt(new Date())
//                            .amount(BigDecimal.ZERO)
//                            .identityType((byte) -1)
//                            .businessType(UserCommissionBusinessTypeEnum.USER.getType())
//                            .build());
//                }
//            }
//            bonusCountMapper.updateByPrimaryKeySelective(bonusCount);
//        }
    }

    @Override
    public void addOnePartner(User user, Byte isBuyer) {
        Identity result = identityMapper.findOneByUserId(user.getId());

        this.hipoConfig = daoService.getHipoConfigMap();

        // 合伙人允许重复购买，重复购买就等于反复续费，每次购买+1年
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.YEAR, 1);

        // 是否首次创建合伙人
        boolean isCreate = true;

        if (result != null) {
//            if (IsBuyerEnum.BUYER.getType().equals(isBuyer)) {
//                result.setMemberAccount(result.getMemberAccount() + Integer.valueOf(daoService.getHipoConfigValue(HipoConfigEnum.PARTNER_MEMBER_ACCOUNT_COUNT.getConfig())));
//            }

            if (result.getMemberLevel() < UserLevelEnum.MEMBER_L1.getLevel()) {
                result.setMemberLevel(UserLevelEnum.MEMBER_L1.getLevel());
            }
            result.setMemberState(MemberStateEnum.SUPER.getType());


            if (result.getMemberLevel() >= UserLevelEnum.MEMBER_L1.getLevel()) {
                Calendar calendar2 = Calendar.getInstance();
                calendar2.add(Calendar.YEAR, 1);
                if (result.getMemberExpireTime() != null) {
                    if (result.getMemberExpireTime().before(calendar2.getTime())) {
                        if (result.getMemberExpireTime().after(new Date())) {
                            calendar2.setTime(result.getMemberExpireTime());
                            calendar2.add(Calendar.YEAR, 1);
                        }
                        result.setMemberExpireTime(calendar2.getTime());
                    }
                } else {
                    result.setMemberExpireTime(calendar2.getTime());
                }
            }


            if (result.getLevel() < UserLevelEnum.PARTNER_L1.getLevel()) {
                result.setLevel(UserLevelEnum.PARTNER_L1.getLevel());
                result.setType(IdentityTypeEnum.PARTNER.getType());
                result.setPartnerLevel(UserLevelEnum.PARTNER_L1.getLevel());
                result.setIsBuyer(isBuyer);
                result.setPartnerExpireTime(calendar.getTime());
                identityMapper.updateByPrimaryKeySelective(result);

                updateUserLevel(user.getId(), UserLevelEnum.PARTNER_L1.getLevel());
            } else {
                // 如果已经是合伙人，股东或以上，则设置或续期
                if (result.getPartnerLevel().equals(0)) {
                    result.setPartnerLevel(UserLevelEnum.PARTNER_L1.getLevel());
                } else {
                    isCreate = false;
                }
                if (result.getPartnerExpireTime() != null) {
                    if (result.getPartnerExpireTime().after(new Date())) {
                        calendar.setTime(result.getPartnerExpireTime());
                        calendar.add(Calendar.YEAR, 1);
                    }
                    result.setPartnerExpireTime(calendar.getTime());
                } else {
                    result.setPartnerExpireTime(calendar.getTime());
                }
                identityMapper.updateByPrimaryKeySelective(result);
            }

        } else {
            Identity subordinateIdentity = Identity.builder()
                    .userId(user.getId())
                    .singleShop(0L)
                    .level(UserLevelEnum.PARTNER_L1.getLevel())
                    .memberLevel(UserLevelEnum.MEMBER_L1.getLevel())
                    .partnerLevel(UserLevelEnum.PARTNER_L1.getLevel())
                    .shareholderLevel(0)
                    .memberL4Grade(0)
                    .partnerL4Grade(0)
                    .shareholderL4Grade(0)
                    .memberL1Number(0L)
                    .memberL2Number(0L)
                    .memberL3Number(0L)
                    .partnerL1Number(0L)
                    .partnerL2Number(0L)
                    .partnerL3Number(0L)
                    .shareholderL1Number(0L)
                    .shareholderL2Number(0L)
                    .shareholderL3Number(0L)
                    .type(IdentityTypeEnum.PARTNER.getType())
                    .isBuyer(isBuyer)
                    .createdAt(new Date())
                    .updateAt(new Date())
                    .director(DirectorEnum.NORMAL.getType())
                    .anchorLevel(AnchorLevelEnum.NOT_ANCHOR.getLevel())
                    .partnerAccount(0)
                    .areaAccount(0)
                    .teacherLevel(TeacherLevelEnum.DEFAULT.getLevel())
                    .recommendLevel(RecommendLevelEnum.V1.getLevel())
                    .partnerExpireTime(calendar.getTime())
                    .memberState(MemberStateEnum.SUPER.getType())
                    .memberAccount(0)
                    .staticDividend(BigDecimal.ZERO)
                    .dividendEffectTime(null)
                    .shareholderState(ShareholderStateEnum.DEFAULT.getType())
                    .sellCount(0L)
                    .welfare(BigDecimal.ZERO)
                    .commissionCount(0L)
                    .inviteCount(0)
                    .inviteRewardLevel(0)
                    .newZoneBuy(ToggleEnum.OFF.getStatus())
                    .build();
            identityMapper.insert(subordinateIdentity);

            updateUserLevel(user.getId(), UserLevelEnum.PARTNER_L1.getLevel());
        }


        // 获取用户上级
        UserRelationship userRelationship = userRelationshipMapper.findOneBySubordinateId(user.getId());

        Long issueSuperiorId = null;
        if (userRelationship != null) {

            // 只要没绑定，就将上下级状态设置为已绑定
            if (!RelationshipStatusEnum.BIND.getStatus().equals(userRelationship.getStatus())) {
                userRelationship.setStatus(RelationshipStatusEnum.BIND.getStatus());
                userRelationship.setUpdatedAt(new Date());
                userRelationshipMapper.updateByPrimaryKeySelective(userRelationship);
            }

            Long superiorId = userRelationship.getSuperiorId();
            Identity superiorIdentity = identityMapper.findOneByUserId(superiorId);

            // 续费不计入邀请人数，仅首次创建算入，并且是购买者
            if (superiorIdentity != null && isCreate && IsBuyerEnum.BUYER.getType().equals(isBuyer)) {

                if (MemberStateEnum.SUPER.getType().equals(superiorIdentity.getMemberState())) {
                    superiorIdentity.setMemberL1Number(superiorIdentity.getMemberL1Number() + 1);
                    isPromotion(superiorIdentity, IdentityTypeEnum.MEMBER);
                }
                // 发放合伙人一级分销佣金（任何等级）
                issueSuperiorId = superiorId;
            }
        }

        // 加入团队
        groupService.createUserGroup(issueSuperiorId, user);


        // 仅购买者发放嗨币
        if (IsBuyerEnum.BUYER.getType().equals(isBuyer)) {
            // 发放合伙人嗨币
            BigDecimal cardPoint = user.getCardPoint().add(new BigDecimal(this.hipoConfig.get(HipoConfigEnum.PARTNER_CARD_POINT.getConfig())));
            userMapper.updateCardPointById(cardPoint, user.getId());
            cardFlowMapper.insert(CardFlow.builder()
                    .userId(user.getId())
                    .amount(new BigDecimal(this.hipoConfig.get(HipoConfigEnum.PARTNER_CARD_POINT.getConfig())))
                    .tradeType(CardTradeTypeEnum.SYSTEM_GIVING.getTradeType())
                    .type(CardTradeTypeEnum.SYSTEM_GIVING.getType())
                    .cardPoint(cardPoint)
                    .remark("赠送合伙人嗨币")
                    .createdAt(new Date())
                    .build());

            //获得VIP佣金机会
            Integer count = Integer.valueOf(daoService.getHipoConfigValue(HipoConfigEnum.PARTNER_MEMBER_ACCOUNT_COUNT.getConfig()));
            identityMapper.addMemberAccountAndUpdateAtByUserId(count, new Date(), user.getId());
        }
    }

    @Override
    public void addOneShareholder(User user, Byte isBuyer) {
        // 如果身份大于等于董事，说明他已经是董事，则不可以再发放董事身份
        Identity result = identityMapper.findOneByUserId(user.getId());

        this.hipoConfig = daoService.getHipoConfigMap();

        if (result != null) {
            if (result.getLevel() < UserLevelEnum.SHAREHOLDER_L1.getLevel()) {

                if (result.getMemberLevel() < UserLevelEnum.MEMBER_L1.getLevel()) {
                    result.setMemberLevel(UserLevelEnum.MEMBER_L1.getLevel());
                }
                result.setMemberState(MemberStateEnum.SUPER.getType());

                if (result.getMemberLevel() >= UserLevelEnum.MEMBER_L1.getLevel()) {
                    Calendar calendar = Calendar.getInstance();
                    calendar.add(Calendar.YEAR, 1);
                    if (result.getMemberExpireTime() != null) {
                        if (result.getMemberExpireTime().before(calendar.getTime())) {
                            if (result.getMemberExpireTime().after(new Date())) {
                                calendar.setTime(result.getMemberExpireTime());
                                calendar.add(Calendar.YEAR, 1);
                            }
                            result.setMemberExpireTime(calendar.getTime());
                        }
                    } else {
                        result.setMemberExpireTime(calendar.getTime());
                    }
                }


                if (result.getPartnerLevel() < UserLevelEnum.PARTNER_L1.getLevel()) {
                    result.setPartnerLevel(UserLevelEnum.PARTNER_L1.getLevel());
                    Calendar calendar = Calendar.getInstance();
                    calendar.add(Calendar.YEAR, 1);
                    if (result.getPartnerExpireTime() != null) {
                        if (result.getPartnerExpireTime().after(new Date())) {
                            calendar.setTime(result.getPartnerExpireTime());
                            calendar.add(Calendar.YEAR, 1);
                        }
                        result.setPartnerExpireTime(calendar.getTime());
                    } else {
                        result.setPartnerExpireTime(calendar.getTime());
                    }
                }

                result.setSingleShop(getSingleShopId());
                result.setLevel(UserLevelEnum.SHAREHOLDER_L1.getLevel());
                result.setType(IdentityTypeEnum.SHAREHOLDER.getType());
                result.setShareholderLevel(UserLevelEnum.SHAREHOLDER_L1.getLevel());
                result.setIsBuyer(isBuyer);
                result.setPartnerAccount(Integer.valueOf(daoService.getHipoConfigValue(HipoConfigEnum.SHAREHOLDER_PARTNER_ACCOUNT_COUNT.getConfig())) + result.getPartnerAccount());
                result.setAreaAccount(0);
                identityMapper.updateByPrimaryKeySelective(result);

                updateUserLevel(user.getId(), UserLevelEnum.SHAREHOLDER_L1.getLevel());
            } else {
                // 如果已经是董事或以上，则终止，不再发放奖励
                return;
            }
        } else {
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.YEAR, 1);
            Identity subordinateIdentity = Identity.builder()
                    .userId(user.getId())
                    .singleShop(getSingleShopId())
                    .level(IsBuyerEnum.BUYER.getType().equals(isBuyer) ? UserLevelEnum.SHAREHOLDER_L2.getLevel() : UserLevelEnum.SHAREHOLDER_L1.getLevel())
                    .memberLevel(UserLevelEnum.MEMBER_L1.getLevel())
                    .partnerLevel(UserLevelEnum.PARTNER_L1.getLevel())
                    .shareholderLevel(UserLevelEnum.SHAREHOLDER_L1.getLevel())
                    .memberL4Grade(0)
                    .partnerL4Grade(0)
                    .shareholderL4Grade(0)
                    .memberL1Number(0L)
                    .memberL2Number(0L)
                    .memberL3Number(0L)
                    .partnerL1Number(0L)
                    .partnerL2Number(0L)
                    .partnerL3Number(0L)
                    .shareholderL1Number(0L)
                    .shareholderL2Number(0L)
                    .shareholderL3Number(0L)
                    .type(IdentityTypeEnum.SHAREHOLDER.getType())
                    .isBuyer(isBuyer)
                    .createdAt(new Date())
                    .updateAt(new Date())
                    .director(DirectorEnum.NORMAL.getType())
                    .anchorLevel(AnchorLevelEnum.NOT_ANCHOR.getLevel())
                    .partnerAccount(Integer.valueOf(daoService.getHipoConfigValue(HipoConfigEnum.SHAREHOLDER_PARTNER_ACCOUNT_COUNT.getConfig())))
                    .areaAccount(0)
                    .teacherLevel(TeacherLevelEnum.DEFAULT.getLevel())
                    .recommendLevel(RecommendLevelEnum.V1.getLevel())
                    .memberState(MemberStateEnum.SUPER.getType())
                    .memberAccount(0)
                    .partnerExpireTime(IsBuyerEnum.BUYER.getType().equals(isBuyer) ? calendar.getTime() : new Date())
                    .memberExpireTime(calendar.getTime())
                    .staticDividend(BigDecimal.ZERO)
                    .dividendEffectTime(null)
                    .shareholderState(ShareholderStateEnum.DEFAULT.getType())
                    .sellCount(0L)
                    .welfare(BigDecimal.ZERO)
                    .commissionCount(0L)
                    .inviteCount(0)
                    .inviteRewardLevel(0)
                    .newZoneBuy(ToggleEnum.OFF.getStatus())
                    .build();
            identityMapper.insert(subordinateIdentity);

            updateUserLevel(user.getId(), UserLevelEnum.SHAREHOLDER_L1.getLevel());
        }

        // 获取用户上级
        UserRelationship userRelationship = userRelationshipMapper.findOneBySubordinateId(user.getId());

        Long issueSuperiorId = null;
        if (userRelationship != null) {
            if (!RelationshipStatusEnum.BIND.getStatus().equals(userRelationship.getStatus())) {
                // 只要没绑定，就将上下级状态设置为已绑定
                userRelationship.setStatus(RelationshipStatusEnum.BIND.getStatus());
                userRelationship.setUpdatedAt(new Date());
                userRelationshipMapper.updateByPrimaryKeySelective(userRelationship);
            }

            Long superiorId = userRelationship.getSuperiorId();
            Identity superiorIdentity = identityMapper.findOneByUserId(superiorId);
            if (superiorIdentity != null && IsBuyerEnum.BUYER.getType().equals(isBuyer)) {
                // 如果上级有运营中心身份，则升级运营中心线
                if (IdentityTypeEnum.SHAREHOLDER.getType().equals(superiorIdentity.getType())) {
                    superiorIdentity.setShareholderL1Number(superiorIdentity.getShareholderL1Number() + 1);
                    isPromotion(superiorIdentity, IdentityTypeEnum.SHAREHOLDER);
                }

                // 发放股东一级分销佣金（任何等级）
                issueSuperiorId = superiorId;
            }
        }

        // 加入团队
        groupService.createUserGroup(issueSuperiorId, user);

        // 晋级主席计数，只有购买的，才进行计数

//        if (IsBuyerEnum.BUYER.getType().equals(isBuyer)) {
//            // 这里单纯的记录人头总数，董事的晋级奖励已经改成按业绩计算，先人为控制
//            BonusCount bonusCount = bonusCountMapper.findOneByRewardType(RewardTypeEnum.SHAREHOLDER_L4.getType());
//            bonusCount.setCount(bonusCount.getCount() + 1L);
//            bonusCountMapper.updateByPrimaryKeySelective(bonusCount);
//        }

        // 购买运营中心，现在算成增加一单会员
        if (IsBuyerEnum.BUYER.getType().equals(isBuyer)) {
            // 晋级会员计数
            BonusCount bonusCount = bonusCountMapper.findOneByRewardType(RewardTypeEnum.MEMBER_L4.getType());
            bonusCount.setCount(bonusCount.getCount() + 1L);
            if (bonusCount.getCount() >= Integer.valueOf(this.hipoConfig.get(HipoConfigEnum.MEMBER_L4_PERIOD.getConfig()))) {
                bonusCount.setCount(0L);
                // 发放晋级总监奖励
                RewardQueue rewardQueue = rewardQueueMapper.findOneByRewardTypeAndQueueStatusForReward(RewardTypeEnum.MEMBER_L4.getType(), ToggleEnum.OFF.getStatus());
                if (rewardQueue != null) {
                    // 要自行到公司领取钱，当前只记录为已经排单
                    rewardQueue.setQueueStatus(ToggleEnum.ON.getStatus());
                    rewardQueue.setUpdateAt(new Date());
                    rewardQueueMapper.updateByPrimaryKeySelective(rewardQueue);

                    // 直接发放佣金
                    // 设置冻结时间
                    Calendar cal = Calendar.getInstance();
                    cal.add(Calendar.DATE, 15);
                    userCommissionMapper.insert(UserCommission.builder()
                            .superiorId(rewardQueue.getUserId())
                            .subordinateId(HIPO_USER_ID)
                            .orderSkuId(null)
                            .commission(rewardQueue.getAmount())
                            .type(UserCommissionTypeEnum.MEMBER_L4_BONUS.getType())
                            .freezeTime(cal.getTime())
                            .status(UserCommissionStatusEnum.FREEZE.getStatus())
                            .relateId(rewardQueue.getId())
                            .remark(UserCommissionTypeEnum.MEMBER_L4_BONUS.getRemark())
                            .createdAt(new Date())
                            .updatedAt(new Date())
                            .amount(BigDecimal.ZERO)
                            .identityType((byte) -1)
                            .businessType(UserCommissionBusinessTypeEnum.USER.getType())
                            .build());
                }
            }
            bonusCountMapper.updateByPrimaryKeySelective(bonusCount);
        }
    }


    @Override
    public void addOneBoss(User user) {
        // 如果身份已是老板，则跳过
        BossIdentity result = bossIdentityMapper.findOneByUserId(user.getId());

        if (result != null) {
            BossIdentity bossIdentity = BossIdentity.builder()
                    .userId(user.getId())
                    .bossLevel(BossLevelEnum.BOSS_L1.getLevel())
                    .bossL4Grade(0)
                    .bossL1Number(0L)
                    .createdAt(new Date())
                    .updatedAt(new Date())
                    .build();
            bossIdentityMapper.insert(bossIdentity);
        }
    }

    private Long getSingleShopId() {
        Long singleShopId = identityMapper.selectMaxSingleShop();
        return singleShopId;
    }

    @Override
    public void updateUserLevel(Long userId, Integer level) {
        groupService.updateUserLevel(level, userId);
    }

    private Integer getNumber(HipoConfigEnum config) {
        return Integer.valueOf(this.hipoConfig.get(config.getConfig()));
    }

    private void isPromotion(Identity identity, IdentityTypeEnum type) {
        // 会员线升级
        if (IdentityTypeEnum.MEMBER.getType().equals(type.getType())) {
            switch (UserLevelEnum.getByLevel(identity.getMemberLevel())) {
//                case MEMBER_L1:
//                    if (identity.getMemberL1Number() >= getNumber(HipoConfigEnum.MEMBER_L2_NEED_L1_COUNT)) {
//                        if (identity.getLevel() < UserLevelEnum.MEMBER_L2.getLevel()) {
//                            identity.setLevel(UserLevelEnum.MEMBER_L2.getLevel());
//                        }
//                        if (identity.getMemberEffectTime() == null) {
//                            identity.setMemberEffectTime(getEffectTime());
//                        }
//                        identity.setMemberLevel(UserLevelEnum.MEMBER_L2.getLevel());
//
//                        UserRelationship userRelationship = userRelationshipMapper.findOneBySubordinateId(identity.getUserId());
//                        if (userRelationship != null) {
//                            Long superiorId = userRelationship.getSuperiorId();
//                            Identity superiorIdentity = identityMapper.findOneByUserId(superiorId);
//                            if (superiorIdentity != null) {
//                                superiorIdentity.setMemberL2Number(superiorIdentity.getMemberL2Number() + 1L);
//                                isPromotion(superiorIdentity, type);
//                            }
//                        }
//                    }
//                    break;
//                case MEMBER_L2:
//                    if (identity.getMemberL1Number() >= getNumber(HipoConfigEnum.MEMBER_L3_NEED_L1_COUNT)
//                            && identity.getMemberL2Number() >= getNumber(HipoConfigEnum.MEMBER_L3_NEED_L2_COUNT)) {
//
//                        if (identity.getLevel() < UserLevelEnum.MEMBER_L3.getLevel()) {
//                            identity.setLevel(UserLevelEnum.MEMBER_L3.getLevel());
//                        }
//                        if (identity.getMemberL3EffectTime() == null) {
//                            identity.setMemberL3EffectTime(getEffectTimeByDay(45));
//                        }
//                        identity.setMemberLevel(UserLevelEnum.MEMBER_L3.getLevel());
//
//                        UserRelationship userRelationship = userRelationshipMapper.findOneBySubordinateId(identity.getUserId());
//                        if (userRelationship != null) {
//                            Long superiorId = userRelationship.getSuperiorId();
//                            Identity superiorIdentity = identityMapper.findOneByUserId(superiorId);
//                            if (superiorIdentity != null) {
//                                superiorIdentity.setMemberL3Number(superiorIdentity.getMemberL3Number() + 1L);
//                                isPromotion(superiorIdentity, type);
//                            }
//                        }
//                    }
//                    break;
//                case MEMBER_L3:
//                    if (identity.getMemberL1Number() >= getNumber(HipoConfigEnum.MEMBER_L4_NEED_L1_COUNT)
//                            && identity.getMemberL3Number() >= getNumber(HipoConfigEnum.MEMBER_L4_NEED_L3_COUNT)
//                    ) {
//                        if (identity.getLevel() < UserLevelEnum.MEMBER_L4.getLevel()) {
//                            identity.setLevel(UserLevelEnum.MEMBER_L4.getLevel());
//                        }
//                        if (identity.getMemberL4EffectTime() == null) {
//                            identity.setMemberL4EffectTime(getEffectTimeByDay(60));
//                        }
//                        identity.setMemberLevel(UserLevelEnum.MEMBER_L4.getLevel());
//                        identity.setMemberL4Grade(identity.getMemberL4Grade() + 1);
//                        identity.setMemberL1Number(identity.getMemberL1Number() - getNumber(HipoConfigEnum.MEMBER_L4_NEED_L1_COUNT));
//                        identity.setMemberL3Number(identity.getMemberL3Number() - getNumber(HipoConfigEnum.MEMBER_L4_NEED_L3_COUNT));
//
//                        // 再发放一个晋级股东奖励排单（购买和赠送升级到此时，都有奖励）
//                        rewardQueueMapper.insert(RewardQueue.builder()
//                                .userId(identity.getUserId())
//                                .level(UserLevelEnum.MEMBER_L4.getLevel())
//                                .queueStatus(ToggleEnum.OFF.getStatus())
//                                .rewardStatus(ToggleEnum.OFF.getStatus())
//                                .createdAt(new Date())
//                                .updateAt(new Date())
//                                .amount(new BigDecimal(this.hipoConfig.get(HipoConfigEnum.MEMBER_L4_BONUS.getConfig())))
//                                .type(RewardQueueTypeEnum.NORMAL.getType())
//                                .rewardType(RewardTypeEnum.MEMBER_L4.getType())
//                                .build());
//                    }
//                    break;
//                case MEMBER_L4:
//                    if (identity.getMemberL1Number() >= getNumber(HipoConfigEnum.MEMBER_L4_NEED_L1_COUNT)
//                            && identity.getMemberL3Number() >= getNumber(HipoConfigEnum.MEMBER_L4_NEED_L3_COUNT)
//                    ) {
//                        // 仅升级钻石等级
//                        identity.setMemberL4Grade(identity.getMemberL4Grade() + 1);
//                        identity.setMemberL1Number(identity.getMemberL1Number() - getNumber(HipoConfigEnum.MEMBER_L4_NEED_L1_COUNT));
//                        identity.setMemberL3Number(identity.getMemberL3Number() - getNumber(HipoConfigEnum.MEMBER_L4_NEED_L3_COUNT));
//
//                        // 再发放一个晋级股东奖励排单（购买和赠送升级到此时，都有奖励）
//                        rewardQueueMapper.insert(RewardQueue.builder()
//                                .userId(identity.getUserId())
//                                .level(UserLevelEnum.MEMBER_L4.getLevel())
//                                .queueStatus(ToggleEnum.OFF.getStatus())
//                                .rewardStatus(ToggleEnum.OFF.getStatus())
//                                .createdAt(new Date())
//                                .updateAt(new Date())
//                                .amount(new BigDecimal(this.hipoConfig.get(HipoConfigEnum.MEMBER_L4_BONUS.getConfig())))
//                                .type(RewardQueueTypeEnum.NORMAL.getType())
//                                .rewardType(RewardTypeEnum.MEMBER_L4.getType())
//                                .build());
//                    }
//                    break;
                default:
                    break;
            }
        }

        // 合伙人线升级
        if (IdentityTypeEnum.PARTNER.getType().equals(type.getType())) {
            switch (UserLevelEnum.getByLevel(identity.getPartnerLevel())) {
//                case PARTNER_L1:
//                    if (identity.getPartnerL1Number() >= getNumber(HipoConfigEnum.PARTNER_L2_NEED_L1_COUNT)) {
//                        if (identity.getLevel() < UserLevelEnum.PARTNER_L2.getLevel()) {
//                            identity.setLevel(UserLevelEnum.PARTNER_L2.getLevel());
//                        }
//                        identity.setPartnerLevel(UserLevelEnum.PARTNER_L2.getLevel());
//
//                        UserRelationship userRelationship = userRelationshipMapper.findOneBySubordinateId(identity.getUserId());
//                        if (userRelationship != null) {
//                            Long superiorId = userRelationship.getSuperiorId();
//                            Identity superiorIdentity = identityMapper.findOneByUserId(superiorId);
//                            if (superiorIdentity != null) {
//                                superiorIdentity.setPartnerL2Number(superiorIdentity.getPartnerL2Number() + 1L);
//                                isPromotion(superiorIdentity, type);
//                            }
//                        }
//                    }
//                    break;
//                case PARTNER_L2:
//                    if (identity.getPartnerL1Number() >= getNumber(HipoConfigEnum.PARTNER_L3_NEED_L1_COUNT)
//                            && identity.getPartnerL2Number() >= getNumber(HipoConfigEnum.PARTNER_L3_NEED_L2_COUNT)
//                    ) {
//                        if (identity.getLevel() < UserLevelEnum.PARTNER_L3.getLevel()) {
//                            identity.setLevel(UserLevelEnum.PARTNER_L3.getLevel());
//                        }
//                        identity.setPartnerLevel(UserLevelEnum.PARTNER_L3.getLevel());
//
//                        UserRelationship userRelationship = userRelationshipMapper.findOneBySubordinateId(identity.getUserId());
//                        if (userRelationship != null) {
//                            Long superiorId = userRelationship.getSuperiorId();
//                            Identity superiorIdentity = identityMapper.findOneByUserId(superiorId);
//                            if (superiorIdentity != null) {
//                                superiorIdentity.setPartnerL3Number(superiorIdentity.getPartnerL3Number() + 1L);
//                                isPromotion(superiorIdentity, type);
//                            }
//                        }
//                    }
//                    break;
//                case PARTNER_L3:
//                    if (identity.getPartnerL1Number() >= getNumber(HipoConfigEnum.PARTNER_L4_NEED_L1_COUNT)
//                            && identity.getPartnerL3Number() >= getNumber(HipoConfigEnum.PARTNER_L4_NEED_L3_COUNT)
//                    ) {
//                        if (identity.getLevel() < UserLevelEnum.PARTNER_L4.getLevel()) {
//                            identity.setLevel(UserLevelEnum.PARTNER_L4.getLevel());
//                        }
//                        identity.setPartnerLevel(UserLevelEnum.PARTNER_L4.getLevel());
//                        identity.setPartnerL4Grade(identity.getPartnerL4Grade() + 1);
//                        identity.setPartnerL1Number(identity.getPartnerL1Number() - getNumber(HipoConfigEnum.PARTNER_L4_NEED_L1_COUNT));
//                        identity.setPartnerL3Number(identity.getPartnerL3Number() - getNumber(HipoConfigEnum.PARTNER_L4_NEED_L3_COUNT));
//
//                        // 发放一个晋级董事奖励排单
//                        rewardQueueMapper.insert(RewardQueue.builder()
//                                .userId(identity.getUserId())
//                                .level(UserLevelEnum.PARTNER_L4.getLevel())
//                                .queueStatus(ToggleEnum.OFF.getStatus())
//                                .rewardStatus(ToggleEnum.OFF.getStatus())
//                                .createdAt(new Date())
//                                .updateAt(new Date())
//                                .amount(new BigDecimal(this.hipoConfig.get(HipoConfigEnum.PARTNER_L4_BONUS.getConfig())))
//                                .type(RewardQueueTypeEnum.NORMAL.getType())
//                                .rewardType(RewardTypeEnum.PARTNER_L4.getType())
//                                .build());
//                    }
//                    break;
//                case PARTNER_L4:
//                    if (identity.getPartnerL1Number() >= getNumber(HipoConfigEnum.PARTNER_L4_NEED_L1_COUNT)
//                            && identity.getPartnerL3Number() >= getNumber(HipoConfigEnum.PARTNER_L4_NEED_L3_COUNT)
//                    ) {
//                        // 仅升级股东等级
//                        identity.setPartnerL4Grade(identity.getPartnerL4Grade() + 1);
//                        identity.setPartnerL1Number(identity.getPartnerL1Number() - getNumber(HipoConfigEnum.PARTNER_L4_NEED_L1_COUNT));
//                        identity.setPartnerL3Number(identity.getPartnerL3Number() - getNumber(HipoConfigEnum.PARTNER_L4_NEED_L3_COUNT));
//
//                        // 再发放一个晋级董事奖励排单
//                        rewardQueueMapper.insert(RewardQueue.builder()
//                                .userId(identity.getUserId())
//                                .level(UserLevelEnum.PARTNER_L4.getLevel())
//                                .queueStatus(ToggleEnum.OFF.getStatus())
//                                .rewardStatus(ToggleEnum.OFF.getStatus())
//                                .createdAt(new Date())
//                                .updateAt(new Date())
//                                .amount(new BigDecimal(this.hipoConfig.get(HipoConfigEnum.PARTNER_L4_BONUS.getConfig())))
//                                .type(RewardQueueTypeEnum.NORMAL.getType())
//                                .rewardType(RewardTypeEnum.PARTNER_L4.getType())
//                                .build());
//                    }
//                    break;
                default:
                    break;
            }
        }

        // 运营中心线升级
//        if (IdentityTypeEnum.SHAREHOLDER.getType().equals(type.getType())) {
//            switch (UserLevelEnum.getByLevel(identity.getShareholderLevel())) {
//                case SHAREHOLDER_L1:
//                    if (identity.getShareholderL1Number() >= getNumber(HipoConfigEnum.SHAREHOLDER_L2_NEED_L1_COUNT)) {
//                        if (identity.getShareholderL2EffectTime() == null) {
//                            identity.setShareholderL2EffectTime(getEffectTimeByDay(28));
//                        }
//                        identity.setLevel(UserLevelEnum.SHAREHOLDER_L2.getLevel());
//                        identity.setShareholderLevel(UserLevelEnum.SHAREHOLDER_L2.getLevel());
//
//                        UserRelationship userRelationship = userRelationshipMapper.findOneBySubordinateId(identity.getUserId());
//                        if (userRelationship != null) {
//                            Long superiorId = userRelationship.getSuperiorId();
//                            Identity superiorIdentity = identityMapper.findOneByUserId(superiorId);
//                            if (superiorIdentity != null) {
//                                superiorIdentity.setShareholderL2Number(superiorIdentity.getShareholderL2Number() + 1L);
//                                isPromotion(superiorIdentity, type);
//                            }
//                        }
//                    }
//                    break;
//                case SHAREHOLDER_L2:
//                    if (identity.getShareholderL1Number() >= getNumber(HipoConfigEnum.SHAREHOLDER_L3_NEED_L1_COUNT)
//                            && identity.getShareholderL2Number() >= getNumber(HipoConfigEnum.SHAREHOLDER_L3_NEED_L2_COUNT)
//                    ) {
//                        if (identity.getShareholderL3EffectTime() == null) {
//                            identity.setShareholderL3EffectTime(getEffectTimeByDay(45));
//                        }
//                        identity.setLevel(UserLevelEnum.SHAREHOLDER_L3.getLevel());
//                        identity.setShareholderLevel(UserLevelEnum.SHAREHOLDER_L3.getLevel());
//
//                        UserRelationship userRelationship = userRelationshipMapper.findOneBySubordinateId(identity.getUserId());
//                        if (userRelationship != null) {
//                            Long superiorId = userRelationship.getSuperiorId();
//                            Identity superiorIdentity = identityMapper.findOneByUserId(superiorId);
//                            if (superiorIdentity != null) {
//                                superiorIdentity.setShareholderL3Number(superiorIdentity.getShareholderL3Number() + 1L);
//                                isPromotion(superiorIdentity, type);
//                            }
//                        }
//                    }
//                    break;
//                case SHAREHOLDER_L3:
//                    if (identity.getShareholderL1Number() >= getNumber(HipoConfigEnum.SHAREHOLDER_L4_NEED_L1_COUNT)
//                            && identity.getShareholderL3Number() >= getNumber(HipoConfigEnum.SHAREHOLDER_L4_NEED_L3_COUNT)
//                    ) {
//                        if (identity.getShareholderL4EffectTime() == null) {
//                            identity.setShareholderL4EffectTime(getEffectTimeByDay(60));
//                        }
//                        identity.setLevel(UserLevelEnum.SHAREHOLDER_L4.getLevel());
//                        identity.setShareholderLevel(UserLevelEnum.SHAREHOLDER_L4.getLevel());
//                        identity.setShareholderL4Grade(identity.getShareholderL4Grade() + 1);
//                        identity.setShareholderL1Number(identity.getShareholderL1Number() - getNumber(HipoConfigEnum.SHAREHOLDER_L4_NEED_L1_COUNT));
//                        identity.setShareholderL3Number(identity.getShareholderL3Number() - getNumber(HipoConfigEnum.SHAREHOLDER_L4_NEED_L3_COUNT));
//
//                        // 发放一个晋级主席奖励排单
////                        if (IsBuyerEnum.BUYER.getType().equals(identity.getIsBuyer())) {
////                            rewardQueueMapper.insert(RewardQueue.builder()
////                                    .userId(identity.getUserId())
////                                    .level(UserLevelEnum.SHAREHOLDER_L4.getLevel())
////                                    .queueStatus(ToggleEnum.OFF.getStatus())
////                                    .rewardStatus(ToggleEnum.OFF.getStatus())
////                                    .createdAt(new Date())
////                                    .updateAt(new Date())
////                                    .amount(new BigDecimal(this.hipoConfig.get(HipoConfigEnum.SHAREHOLDER_L4_BONUS.getConfig())))
////                                    .type(RewardQueueTypeEnum.NORMAL.getType())
////                                    .rewardType(RewardTypeEnum.SHAREHOLDER_L4.getType())
////                                    .build());
////                        }
//                    }
//                    break;
//                case SHAREHOLDER_L4:
//                    if (identity.getShareholderL1Number() >= getNumber(HipoConfigEnum.SHAREHOLDER_L4_NEED_L1_COUNT)
//                            && identity.getShareholderL3Number() >= getNumber(HipoConfigEnum.SHAREHOLDER_L4_NEED_L3_COUNT)
//                    ) {
//                        // 仅升级主席等级
//                        identity.setShareholderL4Grade(identity.getShareholderL4Grade() + 1);
//                        identity.setShareholderL1Number(identity.getShareholderL1Number() - getNumber(HipoConfigEnum.SHAREHOLDER_L4_NEED_L1_COUNT));
//                        identity.setShareholderL3Number(identity.getShareholderL3Number() - getNumber(HipoConfigEnum.SHAREHOLDER_L4_NEED_L3_COUNT));
//
//                        // 再发放一个晋级主席奖励排单
////                        if (IsBuyerEnum.BUYER.getType().equals(identity.getIsBuyer())) {
////                            rewardQueueMapper.insert(RewardQueue.builder()
////                                    .userId(identity.getUserId())
////                                    .level(UserLevelEnum.SHAREHOLDER_L4.getLevel())
////                                    .queueStatus(ToggleEnum.OFF.getStatus())
////                                    .rewardStatus(ToggleEnum.OFF.getStatus())
////                                    .createdAt(new Date())
////                                    .updateAt(new Date())
////                                    .amount(new BigDecimal(this.hipoConfig.get(HipoConfigEnum.SHAREHOLDER_L4_BONUS.getConfig())))
////                                    .type(RewardQueueTypeEnum.NORMAL.getType())
////                                    .rewardType(RewardTypeEnum.SHAREHOLDER_L4.getType())
////                                    .build());
////                        }
//                    }
//                    break;
//                default:
//                    break;
//            }
//        }


        // 无论他是否升级了，都重新设置他的等级
        updateUserLevel(identity.getUserId(), identity.getLevel());
        identityMapper.updateByPrimaryKeySelective(identity);
    }

    @Override
    public void isBossPromotion(BossIdentity identity) {
        switch (BossLevelEnum.getByLevel(identity.getBossLevel())) {
            case BOSS_L1:
                if (identity.getBossL1Number() >= getNumber(HipoConfigEnum.BOSS_L2_NEED_L1_COUNT)) {
                    identity.setBossLevel(BossLevelEnum.BOSS_L2.getLevel());
                }
                break;
            case BOSS_L2:
                if (identity.getBossL1Number() >= getNumber(HipoConfigEnum.BOSS_L3_NEED_L1_COUNT)) {
                    identity.setBossLevel(BossLevelEnum.BOSS_L3.getLevel());
                }
                break;
            case BOSS_L3:
                if (identity.getBossL1Number() >= getNumber(HipoConfigEnum.BOSS_L4_NEED_L1_COUNT)) {
                    identity.setBossLevel(BossLevelEnum.BOSS_L4.getLevel());
                }
                break;
            default:
                break;
        }

        // 无论他是否升级了，都重新设置他的等级
        bossIdentityMapper.updateBossLevelById(identity.getBossLevel(), identity.getId());
    }
}